#include  <stdio.h>
#include  "doxon.h"
#include  "pcb.h"
#include  "thread.h"
#include  "ptest.h"

#include  "semaphor.h"

/** 
 * @brief Sluzi za komunikaciju izmedju Consumer-a i Producer-a
 */
static int buffer_char = 0;

static Semaphore mutex_prod(0);
/* Consumer prvi pocinje sa radom. Mora da se ima sta da se trosi :) */
static Semaphore mutex_cons(1);
static Semaphore wait1(0);
static Semaphore wait2(0);
static Semaphore interrupt_(0);

int semPreempt = 1;

Consumer *cns;
Producer *prd;

void tick(){}

/** 
 * @brief Maksimalni broj petlji u svakoj niti
 */
#define MAX_LOOPS 5
#define WAIT      10
Producer::Producer():Thread(-1) {}

Consumer::Consumer():Thread(-1) {}

void Producer::run() {
    static int prod = 'a';
    int return_wait;
    int return_interrupt = 0;
    int i;
    /*
    return_wait = wait1.wait(WAIT);
    lock();
    printf("Wait in Producer, returned: %d\n", return_wait);
    unlock();
    */
//    return_interrupt = interrupt_.wait(0);

    for (i = 0; i < MAX_LOOPS; i++) {
        return_wait = mutex_cons.wait(0);
        buffer_char = prod++;
        mutex_prod.signal();
    }
    putchar('\n');
    lock();
    printf("Last in mutex_cons in Producer returned %d\n", return_wait);
    printf("Return in interrupt %d\n", return_interrupt);
    unlock();
}

void Consumer::run() {
    int i;
    int return_wait;
    /*
    return_wait = wait2.wait(WAIT+100);
    lock();
    printf("Wait in Consumer, returned: %d\n", return_wait);
    unlock();
    */
//    prd->Interrupt();
    for (i = 0; i < MAX_LOOPS; i++) {
        return_wait = mutex_prod.wait(0);
        putchar( buffer_char );
        buffer_char = 0;
        mutex_cons.signal();
    }
    lock();
    printf("\nLast in mutex_prod in Consumer returned %d\n", return_wait);
    unlock();
}

int main(int argc, char *argv[])
{
    Doxon::init();
    cns = new Consumer();
    prd = new Producer();

    cns->start();
    prd->start();

    Doxon::halt();

    printf("Happy end.\n");
    return 0;
}
